package org.csu.jpetstoremanagement.controller;

import com.alibaba.fastjson.JSON;
import org.csu.jpetstoremanagement.domain.Order;
import org.csu.jpetstoremanagement.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/orders")
    public String getOrders(Model model) {
        List<Order> orders = orderService.getOrderList();
        model.addAttribute("orders", orders);
        return "/order/orders";
    }

    @GetMapping("/orders/{id}")
    @ResponseBody
    public String getOrder(@PathVariable("id") String orderId, Model model) {
        Order order = orderService.getOrder(Integer.parseInt(orderId));
        return JSON.toJSONString(order);
    }

    @PutMapping("/orders/{id}")
    public String updateOrder(@PathVariable("id") String orderId, Order order, Model model) {
        if (order.getOrderId() == Integer.parseInt(orderId)) {
            orderService.updateOrder(order);
            return "redirect:/orders";
        } else {
            model.addAttribute("msg", "Request does not match actual data");
            return "/common/error";
        }
    }

    @GetMapping("/deleteOrder")
    public String deleteOrder(String orderId, Model model) {
        orderService.deleteOrder(Integer.parseInt(orderId));
        List<Order> orders = orderService.getOrderList();
        model.addAttribute("orders", orders);
        return "redirect:/orders";

    }

    @GetMapping("/sales")
    public String getSales(Model model) {
        return "/order/sales";
    }

    @GetMapping("/weeksale")
    public String getWeekSales(Model model) {

        return "/order/weeksale";
    }

    @GetMapping("/money")
    public String getMoney(Model model) {
        return "/order/money";
    }

    @GetMapping("/updateOut")
    public String updateOut(String orderId, Model model) {
        System.out.println(orderId);
        orderService.updateOut(Integer.parseInt(orderId));
        List<Order> orders = orderService.getOrderList();
        model.addAttribute("orders", orders);
        return "redirect:/orders";
    }

    @GetMapping("/ordersunsent")
    public String getUnSent( Model model) {
        List<Order> orders = orderService.getUnSentOrderList();
        model.addAttribute("orders", orders);
        return "/order/orders";
    }
}
